/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        if (root && subRoot)
        {
            vector<string> s1;
            vector<string> s2;
            serial(root, s1);
            serial(subRoot, s2);
            int res = kmp(s1, s2);
            return res != -1;
        }
        return subRoot == nullptr;
    }

    void serial(TreeNode* pt, vector<string>& path)
    {
        if (pt == nullptr)
            path.push_back("nullptr");
        else
        {
            path.push_back(to_string(pt->val));
            serial(pt->left, path);
            serial(pt->right, path);
        }
    }

    int kmp(vector<string>& s1, vector<string>& s2)
    {
        int m = s1.size(), n = s2.size();
        vector<int> next(n + 5);
        next[0] = -1;
        next[1] = 0;
        int i = 2, cn = 0;
        while (i < n)
        {
            if (isEqual(s2[i - 1], s2[cn]))
                next[i++] = ++cn;
            else if (cn > 0)
                cn = next[cn];
            else
                next[i++] = 0;
        }
        int x = 0, y = 0;
        while (x < m && y < n)
        {
            if (isEqual(s1[x], s2[y]))
            {
                x++;
                y++;
            }
            else if (y == 0)
                x++;
            else
                y = next[y];
        }
        return (y == n) ? x - y : -1;
    }
    bool isEqual(const string& a, const string& b)
    {
        if (a.empty() && b.empty())
            return true;
        if (!a.empty() && !b.empty())
            return !a.compare(b);
        return false;
    }
};
